package 数组算法;

import org.junit.Test;

public class addTwoNumbers2V2 {
    /**
     * 链表的相加 采用的双指针的方式
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dumy = new ListNode(-1);
        ListNode curr = dumy;

        // 标志位置
        int count = 0;

        while (l1 != null || l2 != null) {

            int a = l1 != null ? l1.val : 0;
            int b = l2 != null ? l2.val : 0;

            int c = (a + b + count) % 10;
            count = (a + b + count) / 10;

            curr.next = new ListNode(c);
            curr = curr.next;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (count != 0) {
            curr.next = new ListNode(count);
        }
        return dumy.next;
    }

    @Test
    public void test() {
        ListNode s1 = new ListNode(2);
        ListNode s2 = new ListNode(4);
        ListNode s3 = new ListNode(3);

        s1.next = s2;
        s2.next = s3;

        ListNode n1 = new ListNode(5);
        ListNode n2 = new ListNode(6);
        ListNode n3 = new ListNode(4);
        n1.next = n2;
        n2.next = n3;

        ListNode listNode = addTwoNumbers(s1, n1);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}
